import json
import requests
import base64
import json
import Sunny as SyNet
from pydash import get
import ctypes
import os
import sys


def GetGiftJson():
    """获取快手礼物"""
    try:
        # 尝试寻找礼物文件
        with open('gift.json', 'r', encoding='utf-8') as file:
            content = file.read()
            json_data = json.loads(content)
            return json_data['data']
    except FileNotFoundError:
        # 捕获文件不存在的异常
        url = 'https://live.kuaishou.com/live_api/emoji/allgifts'
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
        }
        response = requests.get(url, headers=headers)
        if response.status_code == 200:
            data = response.text
            json_data = json.loads(data)
            with open('gift.json', 'w', encoding='utf-8') as file:
                file.write(data)
            return json_data['data']
        else:
            print(f"请求失败，状态码：{response.status_code}")


gift_json = GetGiftJson()  # 获取礼物的JSON


def giftIdToName(giftid):
    """ 通过礼物ID获取礼物名字 """
    for item in gift_json:  # type: ignore
        if str(giftid) == item:
            return gift_json[item]['giftName']  # type: ignore


def KsMessage(json_data, type):
    """ 解析快手弹幕消息 """
    if json_data is None:
        return 'err: json_data 不能为 None'
    if type not in [0, 1]:
        return 'err: type 可选值为 0/1'

    barrageMsg = {
        "type": 0,  # 弹幕消息
        "userName": None,
        "userId": None,
        "userSex": None,
        "context": None  # 弹幕内容
    }
    # 用户名解析
    namePath = get(json_data, '[2].value[0].value[1].value[1]', None) if type == 0 else get(
        json_data, '[0].value[1].value[1]', None)
    barrageMsg['userName'] = None if namePath is None else namePath['value'] if namePath['Type'] == 'String' else namePath['note']
    # 用户性别解析
    barrageMsg['userSex'] = get(json_data, '[2].value[0].value[1].value[2].value', None) if type == 0 else get(
        json_data, '[0].value[1].value[2].value', None)
    # 用户ID解析
    barrageMsg['userId'] = get(json_data, '[2].value[0].value[1].value[0].value',
                               None) if type == 0 else get(json_data, '[0].value[1].value[0].value', None)
    # 弹幕消息解析
    contextPath = get(json_data, '[2].value[0].value[3]', None) if type == 0 else get(
        json_data, '[0].value[3]', None)
    try:
        barrageMsg['context'] = None if contextPath is None else contextPath[
            'value'] if contextPath['Type'] == 'String' else contextPath['note']
    except KeyError:
        barrageMsg['context'] = None
    if barrageMsg['context'] is None:
        return None
    else:
        return barrageMsg


def KsGift(json_data):
    """ 解析用户礼物 """
    if json_data is None:
        return 'err: json_data 不能为 None'
    giftMsg = {
        "type": 1,  # 礼物消息
        "userName": None,
        "userId": None,
        "userSex": None,
        "giftId": None,  # 礼物ID
        "giftNumber": None,  # 礼物数量
        "giftValue": None,  # 礼物总价值
        "giftType": None,  # 礼物类型 2048背包礼物 8192抽奖礼物 1正常礼物
    }
    for (index, item) in json_data:
        namePath = get(json_data, '[0].value.[1].value.[1]', None)
        giftMsg['userName'] = None if namePath is None else namePath['note'] if namePath['Type'] == 'StringRaw' else namePath['value']
        giftMsg['userSex'] = get(
            json_data, '[0].value.[1].value.[2].value', None)
        giftMsg['userId'] = get(
            json_data, '[0].value.[1].value.[0].value', None)
        giftMsg['giftId'] = get(json_data, '[0].value.[3].value', None)
        giftMsg['giftNumber'] = get(json_data, '[0].value.[6].value', None)
        giftMsg['giftValue'] = get(json_data, '[0].value.[8].value', None)
        if giftMsg['giftValue'] is not None:
            giftMsg['giftValue'] = int(giftMsg['giftValue']) - 1
        giftMsg['giftType'] = get(json_data, '[0].value.[14].value', None)
        if giftMsg['giftId'] is None or giftMsg['giftNumber'] is None or giftMsg['giftValue'] is None or giftMsg['giftType'] is None:
            return None
        else:
            return giftMsg


def base64ToPbJson(base):
    """将 Base64 编码的字符串解码为字节数据"""
    decoded_bytes = base64.b64decode(base)
    bin = SyNet.Gzip解压缩(decoded_bytes)
    str_data = SyNet.PB转PbJSON(bin)
    if str_data is not None:
        return json.loads(str_data)
    else:
        return None


def is_admin():
    """检查当前用户是否具有管理员权限"""
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False


def get_resource_path(relative_path):
    """在Python脚本中，可以使用sys._MEIPASS变量来访问嵌入的资源 """
    """请注意，sys._MEIPASS变量只有在打包成exe后才存在，因此在开发过程中需要捕获AttributeError异常，并回退到使用当前工作目录的路径。 """
    try:
        base_path = sys._MEIPASS  # type: ignore
    except AttributeError:
        base_path = os.path.abspath(".")
    return os.path.normpath(os.path.join(base_path, relative_path))
